package com.huhao.wshare.Dynamic;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.VideoView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.huhao.wshare.R;

import java.util.List;

public class DynamicAdapter extends RecyclerView.Adapter<DynamicAdapter.DynamicViewHolder> {

    private Context context;
    private List<DynamicItem> dynamicList;
    private OnImageClickListener onImageClickListener;
    private OnImageStateChangeListener onImageStateChangeListener;
    private OnLikeClickListener onLikeClickListener;
    private OnCommentSendListener onCommentSendListener;
    private OnCommentDeleteListener onCommentDeleteListener; // 添加评论删除监听器

    // 添加点赞点击接口
    public interface OnLikeClickListener {
        void onLikeClick(int dynamicId, int position, boolean isLiked);
    }

    // 添加评论发送接口
    public interface OnCommentSendListener {
        void onCommentSend(int dynamicId, int position, String commentContent);
    }

    // 添加评论删除接口
    public interface OnCommentDeleteListener {
        void onCommentDelete(int commentId, int dynamicPosition, int commentPosition);
    }

    public interface OnImageStateChangeListener {
        void onImageOpened();
        void onImageClosed();
    }
    public interface OnImageClickListener {
        void onImageClick(List<String> imageUrls, int position);
    }
    // 更新构造函数以包含点赞监听器、评论发送监听器和评论删除监听器
    public DynamicAdapter(Context context, List<DynamicItem> dynamicList, OnImageClickListener onImageClickListener,
                          OnImageStateChangeListener onImageStateChangeListener, OnLikeClickListener onLikeClickListener,
                          OnCommentSendListener onCommentSendListener, OnCommentDeleteListener onCommentDeleteListener) {
        this.context = context;
        this.dynamicList = dynamicList;
        this.onImageClickListener = onImageClickListener;
        this.onImageStateChangeListener = onImageStateChangeListener;
        this.onLikeClickListener = onLikeClickListener;
        this.onCommentSendListener = onCommentSendListener;
        this.onCommentDeleteListener = onCommentDeleteListener;
    }

    // 重载构造函数以保持向后兼容性
    public DynamicAdapter(Context context, List<DynamicItem> dynamicList, OnImageClickListener onImageClickListener,
                          OnImageStateChangeListener onImageStateChangeListener, OnLikeClickListener onLikeClickListener,
                          OnCommentSendListener onCommentSendListener) {
        this(context, dynamicList, onImageClickListener, onImageStateChangeListener, onLikeClickListener,
                onCommentSendListener, null);
    }

    @NonNull
    @Override
    public DynamicViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.dynamic_item, parent, false);
        return new DynamicViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull DynamicViewHolder holder, int position) {
        DynamicItem item = dynamicList.get(position);
        // 处理作者信息
        if (item.getAuthor() != null) {
            String remark = item.getAuthor().getRemark();
            String username = item.getAuthor().getUsername();
            String displayName = (remark != null && !remark.isEmpty() && !"null".equals(remark)) ? remark :
                    (username != null && !username.isEmpty() && !"null".equals(username)) ? username : "匿名用户";
            holder.tvItemName.setText(displayName);
            if (item.getAuthor().getAvatar() != null && !item.getAuthor().getAvatar().isEmpty() && !item.getAuthor().getAvatar().equals("null")) {
                Glide.with(context).load(item.getAuthor().getAvatar()).into(holder.ivItemAvatar);
            } else {
                // 根据 gender 设置默认头像
                String gender = item.getAuthor().getGender();
                if ("man".equals(gender)) {
                    holder.ivItemAvatar.setImageResource(R.drawable.default_avatar_man);
                } else if ("woman".equals(gender)) {
                    holder.ivItemAvatar.setImageResource(R.drawable.default_avatar_woman);
                } else {
                    holder.ivItemAvatar.setImageResource(R.drawable.default_avatar_man);
                }
            }
        } else {
            holder.tvItemName.setText("匿名用户");
            holder.ivItemAvatar.setImageResource(R.drawable.default_avatar_man);
        }
        // 处理文本内容
        if (!item.getTextContent().isEmpty() && !item.getTextContent().equals("null")) {
            holder.tvItemContentText.setText(item.getTextContent());
            holder.tvItemContentText.setVisibility(View.VISIBLE);
        } else {
            holder.tvItemContentText.setVisibility(View.GONE);
        }

        // 处理图片
        if (!item.getImageUrls().isEmpty()) {
            holder.rvItemContentImages.setVisibility(View.VISIBLE);
            ImageAdapter imageAdapter = new ImageAdapter(context, item.getImageUrls(), (imageUrl, imagePosition) -> {
                if (onImageClickListener != null) {
                    Log.d("ImageClick", "Clicked image position: " + imagePosition);
                    onImageClickListener.onImageClick(item.getImageUrls(), imagePosition);
                }
                if (onImageStateChangeListener != null) {
                    onImageStateChangeListener.onImageOpened();
                }
            });
            holder.rvItemContentImages.setAdapter(imageAdapter);
            holder.rvItemContentImages.setLayoutManager(new GridLayoutManager(context, 3));
        } else {
            holder.rvItemContentImages.setVisibility(View.GONE);
        }

        // 处理视频
        if (item.getVideo() != null && !item.getVideo().isEmpty() && !item.getVideo().equals("null")) {
            holder.vvItemContentVideo.setVisibility(View.VISIBLE);
            // 这里需要添加视频播放逻辑
        } else {
            holder.vvItemContentVideo.setVisibility(View.GONE);
        }

        // 实现点赞功能
        // 设置点赞图标状态
        if (item.isLikedByCurrentUser()) {
            holder.btnLike.setImageResource(R.drawable.ic_liked);
        } else {
            holder.btnLike.setImageResource(R.drawable.ic_like);
        }

        // 点赞点击事件
        holder.btnLike.setOnClickListener(v -> {
            if (onLikeClickListener != null) {
                onLikeClickListener.onLikeClick(item.getId(), position, item.isLikedByCurrentUser());
            }
        });

        // 显示点赞用户列表
        if (item.getLikers() != null && !item.getLikers().isEmpty()) {
            holder.llLikeUsers.setVisibility(View.VISIBLE);
            StringBuilder likeUsersText = new StringBuilder();
            for (int i = 0; i < item.getLikers().size(); i++) {
                if (i > 0) likeUsersText.append(", ");
                // 使用remark或username显示
                Author liker = item.getLikers().get(i);
                String displayName = (liker.getRemark() != null && !liker.getRemark().isEmpty() && !"null".equals(liker.getRemark())) ?
                        liker.getRemark() : liker.getUsername();
                likeUsersText.append(displayName);
            }
            holder.tvLikeUsers.setText(likeUsersText.toString());
        } else {
            holder.llLikeUsers.setVisibility(View.GONE);
        }

        // 显示评论列表
        if (item.getComments() != null && !item.getComments().isEmpty()) {
            holder.llComments.setVisibility(View.VISIBLE);
            holder.llComments.removeAllViews(); // 清除之前的评论视图

            for (int i = 0; i < item.getComments().size(); i++) {
                Comment comment = item.getComments().get(i);
                // 创建评论视图
                TextView commentView = new TextView(context);
                commentView.setTextSize(12);
                commentView.setTextColor(context.getResources().getColor(R.color.dark_background));

                // 获取评论作者的显示名称
                Author commentAuthor = comment.getAuthor();
                String authorName = (commentAuthor.getRemark() != null && !commentAuthor.getRemark().isEmpty() && !"null".equals(commentAuthor.getRemark())) ?
                        commentAuthor.getRemark() : commentAuthor.getUsername();

                // 设置评论文本为 "user: content" 格式
                String commentText = authorName + ": " + comment.getContent();
                commentView.setText(commentText);

                // 添加长按删除功能（如果提供了删除监听器）
                if (onCommentDeleteListener != null) {
                    final int commentPosition = i;
                    commentView.setOnLongClickListener(v -> {
                        // 显示确认删除对话框
                        new android.app.AlertDialog.Builder(context)
                                .setTitle("删除评论")
                                .setMessage("确定要删除这条评论吗？")
                                .setPositiveButton("删除", (dialog, which) -> {
                                    // 用户确认删除，调用删除监听器
                                    onCommentDeleteListener.onCommentDelete(comment.getId(), position, commentPosition);
                                })
                                .setNegativeButton("取消", null)
                                .show();
                        return true;
                    });
                }

                // 添加到评论容器中
                holder.llComments.addView(commentView);
            }
        } else {
            holder.llComments.setVisibility(View.GONE);
        }

        // 评论按钮点击事件
        holder.btnComment.setOnClickListener(v -> {
            // 切换评论输入区域的可见性
            if (holder.llCommentInput.getVisibility() == View.GONE) {
                holder.llCommentInput.setVisibility(View.VISIBLE);
                holder.etCommentInput.requestFocus();
            } else {
                holder.llCommentInput.setVisibility(View.GONE);
                holder.etCommentInput.setText(""); // 清空输入框
            }
        });

        // 发送评论按钮点击事件
        holder.btnSendComment.setOnClickListener(v -> {
            String commentContent = holder.etCommentInput.getText().toString().trim();
            if (!commentContent.isEmpty() && onCommentSendListener != null) {
                onCommentSendListener.onCommentSend(item.getId(), position, commentContent);
                holder.etCommentInput.setText(""); // 清空输入框
                holder.llCommentInput.setVisibility(View.GONE); // 隐藏输入区域
            }
        });
    }


    @Override
    public int getItemCount() {
        return dynamicList.size();
    }

    public static class DynamicViewHolder extends RecyclerView.ViewHolder {
        ImageView ivItemAvatar;
        TextView tvItemName;
        TextView tvItemContentText;
        RecyclerView rvItemContentImages;
        VideoView vvItemContentVideo;
        ImageView btnLike;
        LinearLayout llLikeUsers;
        TextView tvLikeUsers;
        LinearLayout llComments;
        ImageView btnComment;
        LinearLayout llCommentInput;
        EditText etCommentInput;
        Button btnSendComment;

        public DynamicViewHolder(@NonNull View itemView) {
            super(itemView);
            ivItemAvatar = itemView.findViewById(R.id.ivItemAvatar);
            tvItemName = itemView.findViewById(R.id.tvItemName);
            tvItemContentText = itemView.findViewById(R.id.tvItemContentText);
            rvItemContentImages = itemView.findViewById(R.id.rvItemContentImages);
            vvItemContentVideo = itemView.findViewById(R.id.vvItemContentVideo);
            btnLike = itemView.findViewById(R.id.btnLike);
            llLikeUsers = itemView.findViewById(R.id.llLikeUsers);
            tvLikeUsers = itemView.findViewById(R.id.tvLikeUsers);
            llComments = itemView.findViewById(R.id.llComments);
            btnComment = itemView.findViewById(R.id.btnComment);
            llCommentInput = itemView.findViewById(R.id.llCommentInput);
            etCommentInput = itemView.findViewById(R.id.etCommentInput);
            btnSendComment = itemView.findViewById(R.id.btnSendComment);
        }
    }
}